

import pyqtgraph as pg
import numpy as np

class DrawLine:
    def __init__(self):
        self.x = []
        self.y = []
        self.plot = None
        self.win = None
        self.__setpoint = 800

    def createPlot(self):
        self.win = pg.GraphicsLayoutWidget(show=True)
        self.win.setBackground('w')
        self.plot_win = self.win.addPlot()
        self.plot_win.showGrid(x=True, y=True)  # 把X和Y的表格打开
        self.plot_win.setRange(xRange=[0, self.__setpoint], padding=0)
        # self.plot_win.setLabel(axis='left', text='y / V')  # 靠左
        # self.plot_win.setLabel(axis='bottom', text='x / point')
        # self.plot_win.setTitle('y = sin(x)')  # 表格的名字

        # 创建一个标签来显示坐标
        self.label = pg.LabelItem(justify='right')
        self.win.addItem(self.label)

        # 创建十字线
        self.vLine = pg.InfiniteLine(angle=90, movable=False)
        self.hLine = pg.InfiniteLine(angle=0, movable=False)
        self.plot_win.addItem(self.vLine, ignoreBounds=True)
        self.plot_win.addItem(self.hLine, ignoreBounds=True)


        pen = pg.mkPen(color=(255, 0, 0), width=4)
        self.plot = self.plot_win.plot(pen=pen)
        # self.data = np.random.randint(low=0, high=100, size=800)
        # self.plot.setData(self.data)
        self.plot.setData(self.x,self.y)


        self.plot.scene().sigMouseMoved.connect(self.mouseMoved)

        return self.win

    def mouseMoved(self,evt):
        pos = evt
        if self.plot_win.sceneBoundingRect().contains(pos):
            mousePoint = self.plot_win.vb.mapSceneToView(pos)
            index = int(mousePoint.x())
            if index > 0 and index < len(self.y):# 测试数据需要self.y换成data
                # print(
                #     "x=%0.1f,y1=%0.1f" % (
                #         mousePoint.x(), self.data[index]))
                self.label.setText(f"<span style='font-size: 12pt'>x={mousePoint.x():.0f}<br> y={mousePoint.y():.1f}</span>")
                self.vLine.setPos(mousePoint.x())  #绘制十字光标
                self.hLine.setPos(mousePoint.y())

    def update(self,data):
        if len(self.x) > self.__setpoint:
            self.x = self.x[1:]  # 去掉列表第一个数，取出除第一个数之外的所有数
            self.plot_win.setXRange(self.x[0], self.x[-1] + 1)
        if len(self.x) == 0:
            self.x.append(0)
        else:
            self.x.append(self.x[-1] + 1)  # 增加一个数，增加的数值为最后一个数+1

        # if len(self.y)>self.__setpoint:
        #     self.y = self.y[1:]  # 去掉列表第一个数，取出除第一个数之外的所有数
        self.y.append(data)  #记录所有数据
        self.plot.setData(self.y)  # 更新x轴和y轴的数据

    def resize(self,x,y):
        self.win.resize(int(x*1),int(y*1))